const { Service } = require('egg');

class ScoreService extends Service {
    /**
     * 添加成绩
     */
    async create({ theory, skill, uid }) {
        let sql = `insert into score (theory, skill, uid) values (?, ?, ?)`;
        let params = [theory, skill, uid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 今日成绩是否录入
     * @param {*} param0
     */
    async isRecord({ today, uid }) {
        let sql = `
            select count(0) as count
            from score
            where date_format(create_time, '%Y-%m-%d') = ? and uid = ?
        `;
        let params = [today, uid];
        let res = await this.app.mysql.query(sql, params);
        return res[0].count > 0;
    }

    async readList() {
        let sql = `
            select s.*, u.username, u.nickname
            from score as s
            join user as u on s.uid = u.id
        `;
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 更新一条记录
     * @param {Object} param0 参数值
     */
    async update({ id, theory, skill }) {
        let sql = 'update score set theory = ?, skill = ? where id = ?';
        let params = [theory, skill, id];
        let res = await this.app.mysql.query(sql, params);
        return res;

        // return await this.app.mysql.update('score', row);

        // let sql = `update score ?`;
        // let params = [];

        // // 存在的参数才更新
        // if (theory) {
        //     sql += ' set theory = ?';
        //     params.push(theory);
        // }

        // if (skill) {
        //     sql += theory ? ', set skill = ?' : ' set skill = ?';
        //     params.push(skill);
        // }

        // sql += ' where id = ?';
        // params.push(id);

        // return await this.app.mysql.query(sql, params);
    }

    /**
     * 删除成绩
     * @param {Number} id 成绩记录 id
     */
    async destory(id) {
        let sql = 'delete from score where id = ?';
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = ScoreService;
